/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

const shortDesc = ['h', 'min', 's', 'ms', 'μs', 'ns'];
const longDesc = ['hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond'];
const convertArray = [60 * 60, 60, 1, 1e6, 1e3, 1];

interface Option {
  verbose?: boolean;
  precise?: boolean;
}

export default function (sourceArray: number[], options?: Option) {
  if (!Array.isArray(sourceArray) || sourceArray.length !== 2) {
    return '';
  }
  if (typeof sourceArray[0] !== 'number' || typeof sourceArray[1] !== 'number') {
    return '';
  }

  const verbose = options?.verbose || false;
  const precise = options?.precise || false;

  if (sourceArray[1] < 0) {
    const totalSecs = sourceArray[0] + sourceArray[1] / 1e9;
    sourceArray[0] = parseInt(totalSecs.toString());
    sourceArray[1] = parseFloat((totalSecs % 1).toPrecision(9)) * 1e9;
  }

  return doCalc(sourceArray, verbose, precise);
}

function doCalc(sourceArray: number[], verbose: boolean, precise: boolean) {
  let ret = '';
  for (let i = 0; i < 6; i++) {
    const spot = i < 3 ? 0 : 1;
    let sourceAtStep = sourceArray[spot];
    if (i !== 3 && i !== 0) {
      sourceAtStep = sourceAtStep % convertArray[i - 1];
    }
    if (i === 2) {
      sourceAtStep += sourceArray[1] / 1e9;
    }
    let valueAtStep = sourceAtStep / convertArray[i];
    if (valueAtStep < 1) {
      continue;
    }

    if (verbose) {
      valueAtStep = Math.floor(valueAtStep);
    }
    let stringAtStep;
    if (!precise) {
      const decimals = valueAtStep >= 10 ? 0 : 2;
      stringAtStep = valueAtStep.toFixed(decimals);
    } else {
      stringAtStep = valueAtStep.toString();
    }
    if (stringAtStep.indexOf('.') > -1 && stringAtStep[stringAtStep.length - 1] === '0') {
      stringAtStep = stringAtStep.replace(/\.?0+$/, '');
    }
    if (ret) {
      ret += ' ';
    }
    ret += stringAtStep;
    if (verbose) {
      ret += ` ${longDesc[i]}`;
      if (stringAtStep !== '1') {
        ret += 's';
      }
    } else {
      ret += ` ${shortDesc[i]}`;
    }
    if (!verbose) {
      break;
    }
  }
  return ret;
}
